#! /usr/bin/env python
#coding=utf-8
import  sys,urllib2,json,time
import MySQLdb
import multiprocessing
reload(sys)

host = "drdsjsq4v76a23pa.drds.aliyuncs.com"
user = "hefantest"
passwd = "HEfantv3_9a5"
db = "hefantest"
# host = "drdshmif9192k8au.drds.aliyuncs.com"
# user = "hefandev"
# passwd = "devhfDEV8v97"
# db = "hefandev"
port = 3306
charset='utf8'


lock = multiprocessing.Lock()

url = "http://10.44.205.218:8055/services/imUser/createUser"
#url = "http://10.45.148.233:8055/services/imUser/createUser"
def httpClientGetImToken(userId) :
    reqUrl = "%s?accid=%s&name=%s" % (url,userId,userId)
    req = urllib2.Request(reqUrl)
    res_data = urllib2.urlopen(req, timeout=10)
    resData = json.loads(res_data.read())
    print resData
    if resData["code"] == 1000 and resData["data"] :
        return resData["data"]
    else:
        return ""


def getBachImToken(stepNum):
    resData = []
    for j in range((stepNum-1)*bachNum,(stepNum-1)*bachNum+bachNum):
        if j>=initCount :
            break
        resData.append(str(beginUserId+j))
    return resData;

def saveBachUserInfo(datas) :
    strArray = []
    for data in datas :
        if data:
            imToken = httpClientGetImToken(prefix+data)
            if imToken :
                strArray.append("('%s','%s')"%(data,imToken));
        time.sleep(0.005)
    print "---getImToke---[%d]---"%(len(strArray))
    if len(strArray) > 0 :
        connect = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, port=port, charset=charset)
        cursor = connect.cursor()
        sql = "insert into hf_user_pre_init(user_id,im_token) values " + ",".join(strArray)
        cursor.execute(sql)
        connect.commit()
        cursor.close();
        connect.close()

def GetNewUser(i):
    bachData = getBachImToken(i)
    saveBachUserInfo(bachData)

beginUserId = 1657259
initCount = 100
bachNum = 500
'''测试使用前缀'''
prefix = ""
if __name__ =='__main__' :
    beginTime = time.clock()
    # setp = initCount/bachNum + (1 if initCount%bachNum > 0 else 0);
    # for i in range(1,setp+1) :
    #     bachData = getBachImToken(i)
    #     saveBachUserInfo(bachData)
    #     print "run bach %d end"%(i)
    # connect.close()
    mgr = multiprocessing.Manager()
    # list_mgr = mgr.list(common.stocks)
    threads = []
    setp = initCount/bachNum + (1 if initCount%bachNum > 0 else 0);
    for i in range(1,setp+1) :
        t_thread = multiprocessing.Process(target=GetNewUser,args=(i,))
        print "-----t_thread start [%d]----"%(i)
        t_thread.start();
        threads.append(t_thread)
    for t_thread in threads:
        t_thread.join()
        print "-----t_thread end ----"
    print "user pre int end time:%d s" % (time.clock() - beginTime)
